package com.winit.openapi.claim.controller;

import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONObject;
import com.winit.openapi.claim.builder.TailTraceOrderBuilder;
import com.winit.openapi.claim.util.ClaimOrderRequest;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.controller.BaseController;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.exception.ValidationException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.HttpUtil;

/**
 * 尾程查件对外API接口，分销系统使用
 * 
 * @version <pre>
 * Author	Version		Date		Changes
 * minghao.deng 	1.0  		2018年4月12日 	Created
 *
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "tail/trace/order")
public class TailTraceOrderController extends BaseController {

    private static final Logger   logger = LoggerFactory.getLogger(TailTraceOrderController.class);

    @Resource
    private TailTraceOrderBuilder tailTraceOrderBuilder;

    /**
     * 创建尾程查件单
     * 
     * @param requestMsg
     * @param responseMsg
     * @return
     */
    @RequestMapping(value = "/create")
    public String createOrder(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        Map<String, Object> data = tailTraceOrderBuilder.buildTailTraceOrderCreate(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("TailTrace.addTailTraceOpen");
        request.setData(data);

        postAndGetResult(request, responseMsg);

        return SUCCESS;

    }

    @RequestMapping(value = "/queryOrderList")
    public String queryOrderList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData().toString());
        Map<String, Object> requestData = tailTraceOrderBuilder.buildGetOrderList(json);
        ClaimOrderRequest request = new ClaimOrderRequest();
        request.setService("TailTrace.getTailTraceRows");
        request.setData(requestData);

        postAndGetResult(request, responseMsg);

        return SUCCESS;

    }

    private void postAndGetResult(ClaimOrderRequest request, ResponseMsg responseMsg) {
        String result = HttpUtil.postJson(config.getHelpCenterDomain(), JSONObject.toJSONString(request));
        if (StringUtils.isNotEmpty(result)) {
            JSONObject itemJson;
            try {
                itemJson = JSONObject.parseObject(result);
            } catch (Exception e) {
                logger.error("调用service:" + request.getService() + "返回值异常：" + result);
                throw new ApiException(ErrorCode.ILLEGAL_JSON_STRING);
            }
            String code = itemJson.getString("status");
            responseMsg.setMsg(itemJson.getString("msg"));
            responseMsg.setData(itemJson.get("data"));
            // 1表示操作成功 0表示操作失败，除此之外没有其他错误码
            if ("1".equals(code)) {
                responseMsg.setCode(ErrorCode.SUCCESS);
            } else {
                responseMsg.setCode(ErrorCode.SYSTEM_ERROR);
                throw new ValidationException(ErrorCode.SYSTEM_ERROR, itemJson.getString("msg"));
            }

        } else {
            logger.error("调用service:" + request.getService() + "返回值为空");
            throw new ApiException(ErrorCode.SYSTEM_ERROR);
        }

    }

}
